using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using LastFmLib.API20.Types;
using StaffWarsFm.Lib.Data;

namespace StaffWarsFm.Questions
{
    public class QuestionServiceBase
    {
        public Question GenerateQuestion(ArtistInfo artist, User[] players, User[] connectedUsers)
        {
            var question = GetRandomQuestion();
            
            if(question.GetParameters().Length == 1)
            {
                return (Question)question.Invoke(this, new[] {artist});    
            }
            else if(question.GetParameters().Length == 2)
            {
                return (Question) question.Invoke(this, new[] {players, connectedUsers});
            }

            throw new Exception("Bibble");
        }

        private MethodInfo GetRandomQuestion()
        {
            var methods = GetType()
                .GetMethods()
                .Where(m => 1 == m.GetCustomAttributes(typeof (QuestionAttribute), false).Length)
                .ToArray();

            return methods[Util.Random(methods.Length)];
        }

        protected Answer[] GetAnswers<T>(T correct, Func<T, Answer> transform)
            where T : class 
        {
            return GetAnswers(correct, Cache<T>.Get(3, correct), transform);
        }

        protected Answer[] GetAnswers<T>(T correct, IEnumerable<T> incorrect, Func<T, Answer> transform)
        {
            var answers = incorrect.Select(transform).ToList();
            answers.ForEach(a => a.IsCorrect = false);

            var correctAnswer = transform(correct);
            correctAnswer.IsCorrect = true;
            
            answers.Add(correctAnswer);
            return answers.ToArray();
        }
    }
}
